

export class SrsError extends Error {
    name: string;
    message: string;
    stack: string;

    constructor(name: string, message: string) {
        super(message);
        this.name = name;
        this.message = message;
        this.stack = (new Error()).stack || '';
    }
}

interface SrsRtcPublisherAsync {
    constraints: {
        audio: boolean;
        video: {
            width: {
                ideal: number;
                max: number;
            };
        };
    };
    publish: (url: string) => Promise<any>;
    close: () => void;
    ontrack: (event: { track: MediaStreamTrack }) => void;
    pc: RTCPeerConnection;
    stream: MediaStream;
    __internal: {
        defaultPath: string;
        prepareUrl: (webrtcUrl: string) => any;
        parse: (url: string) => any;
        fill_query: (query_string: string, obj: any) => void;
    };
}

export function SrsRtcPublisherAsync(): SrsRtcPublisherAsync {
    const self: any = {} as SrsRtcPublisherAsync;

    self.constraints = {
        audio: true,
        video: {
            width: { ideal: 320, max: 576 }
        }
    };

    self.publish = async function (url: string): Promise<any> {
        const conf = self.__internal.prepareUrl(url);
        self.pc.addTransceiver("audio", { direction: "sendonly" });
        self.pc.addTransceiver("video", { direction: "sendonly" });

        if (!navigator.mediaDevices && window.location.protocol === 'http:' && window.location.hostname !== 'localhost') {
            throw new SrsError('HttpsRequiredError', `Please use HTTPS or localhost to publish, read https://github.com/ossrs/srs/issues/2762#issuecomment-983147576`);
        }
        const stream: MediaStream = await navigator.mediaDevices.getUserMedia(self.constraints);

        stream.getTracks().forEach(function (track: MediaStreamTrack) {
            self.pc.addTrack(track);
            self.ontrack && self.ontrack({ track: track });
        });

        const offer: RTCSessionDescriptionInit = await self.pc.createOffer();
        await self.pc.setLocalDescription(offer);
        const session:any = await new Promise((resolve, reject) => {
            const data = {
                api: conf.apiUrl, tid: conf.tid, streamurl: conf.streamUrl,
                clientip: null, sdp: offer.sdp
            };
            console.log("Generated offer: ", data);

            const xhr = new XMLHttpRequest();
            xhr.onload = function () {
                if (xhr.readyState !== xhr.DONE) return;
                if (xhr.status !== 200 && xhr.status !== 201) return reject(xhr);
                const data = JSON.parse(xhr.responseText);
                console.log("Got answer: ", data);
                return data.code ? reject(xhr) : resolve(data);
            }
            xhr.open('POST', conf.apiUrl, true);
            xhr.setRequestHeader('Content-type', 'application/json');
            xhr.send(JSON.stringify(data));
        });
        await self.pc.setRemoteDescription(
            new RTCSessionDescription({ type: 'answer', sdp: session.sdp })
        );
        session.simulator = conf.schema + '//' + conf.urlObject.server + ':' + conf.port + '/rtc/v1/nack/';

        return session;
    };

    self.close = function (): void {
        self.pc && self.pc.close();
        self.pc = null;
    };

    self.ontrack = function (event: { track: MediaStreamTrack }): void {
        self.stream.addTrack(event.track);
    };

    self.__internal = {
        defaultPath: '/rtc/v1/publish/',
        prepareUrl: function (webrtcUrl: string): any {
            const urlObject = self.__internal.parse(webrtcUrl);
            let schema = urlObject.user_query.schema;
            schema = schema ? schema + ':' : window.location.protocol;

            let port = urlObject.port || 1985;
            if (schema === 'https:') {
                port = urlObject.port || 443;
            }

            let api = urlObject.user_query.play || self.__internal.defaultPath;
            if (api.lastIndexOf('/') !== api.length - 1) {
                api += '/';
            }

            let apiUrl = schema + '//' + urlObject.server + ':' + port + api;
            for (const key in urlObject.user_query) {
                if (key !== 'api' && key !== 'play') {
                    apiUrl += '&' + key + '=' + urlObject.user_query[key];
                }
            }
            apiUrl = apiUrl.replace(api + '&', api + '?');

            const streamUrl = urlObject.url;
            let titi:any = new Date().getTime() * Math.random() * 100
            return {
                apiUrl: apiUrl, streamUrl: streamUrl, schema: schema, urlObject: urlObject, port: port,
                tid: Number(parseInt(titi)).toString(16).slice(0, 7)
            };
        },
        parse: function (url: string): any {
            const a = document.createElement("a");
            a.href = url.replace("rtmp://", "http://")
                .replace("webrtc://", "http://")
                .replace("rtc://", "http://");

            let vhost = a.hostname;
            let app = a.pathname.substring(1, a.pathname.lastIndexOf("/"));
            const stream = a.pathname.slice(a.pathname.lastIndexOf("/") + 1);

            app = app.replace("...vhost...", "?vhost=");
            if (app.indexOf("?") >= 0) {
                const params = app.slice(app.indexOf("?"));
                app = app.slice(0, app.indexOf("?"));

                if (params.indexOf("vhost=") > 0) {
                    vhost = params.slice(params.indexOf("vhost=") + "vhost=".length);
                    if (vhost.indexOf("&") > 0) {
                        vhost = vhost.slice(0, vhost.indexOf("&"));
                    }
                }
            }

            if (a.hostname === vhost) {
                const re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
                if (re.test(a.hostname)) {
                    vhost = "__defaultVhost__";
                }
            }

            let schema = "rtmp";
            if (url.indexOf("://") > 0) {
                schema = url.slice(0, url.indexOf("://"));
            }

            let port:any = a.port;
            if (!port) {
                if (schema === 'webrtc' && url.indexOf(`webrtc://${a.host}:`) === 0) {
                    port = (url.indexOf(`webrtc://${a.host}:80`) === 0) ? 80 : 443;
                }

                if (schema === 'http') {
                    port = 80;
                } else if (schema === 'https') {
                    port = 443;
                } else if (schema === 'rtmp') {
                    port = 1935;
                }
            }

            const ret:any = {
                url: url,
                schema: schema,
                server: a.hostname, port: port,
                vhost: vhost, app: app, stream: stream
            };
            self.__internal.fill_query(a.search, ret);

            if (!ret.port) {
                if (schema === 'webrtc' || schema === 'rtc') {
                    if (ret.user_query.schema === 'https') {
                        ret.port = 443;
                    } else if (window.location.href.indexOf('https://') === 0) {
                        ret.port = 443;
                    } else {
                        ret.port = 1985;
                    }
                }
            }

            return ret;
        },
        fill_query: function (query_string: string, obj: any): void {
            obj.user_query = {};

            if (query_string.length === 0) {
                return;
            }

            if (query_string.indexOf("?") >= 0) {
                query_string = query_string.split("?")[1];
            }

            const queries = query_string.split("&");
            for (let i = 0; i < queries.length; i++) {
                const elem = queries[i];
                const query = elem.split("=");
                obj[query[0]] = query[1];
                obj.user_query[query[0]] = query[1];
            }

            if (obj.domain) {
                obj.vhost = obj.domain;
            }
        }
    };
    let str:any = null
    self.pc = new RTCPeerConnection(str);
    self.stream = new MediaStream();

    return self;
}

interface SrsRtcPlayerAsync {
    play: (url: string) => Promise<any>;
    close: () => void;
    ontrack: (event: { track: MediaStreamTrack }) => void;
    pc: RTCPeerConnection;
    stream: MediaStream;
    __internal: {
        defaultPath: string;
        prepareUrl: (webrtcUrl: string) => any;
        parse: (url: string) => any;
        fill_query: (query_string: string, obj: any) => void;
    };
}

export function SrsRtcPlayerAsync(): SrsRtcPlayerAsync {
    const self: any = {} as SrsRtcPlayerAsync;

    self.play = async function (url: string): Promise<any> {
        const conf = self.__internal.prepareUrl(url);
        self.pc.addTransceiver("audio", { direction: "recvonly" });
        self.pc.addTransceiver("video", { direction: "recvonly" });

        const offer: RTCSessionDescriptionInit = await self.pc.createOffer();
        await self.pc.setLocalDescription(offer);
        const session:any = await new Promise((resolve, reject) => {
            const data = {
                api: conf.apiUrl, tid: conf.tid, streamurl: conf.streamUrl,
                clientip: null, sdp: offer.sdp
            };
            console.log("Generated offer: ", data);

            const xhr = new XMLHttpRequest();
            xhr.onload = function () {
                if (xhr.readyState !== xhr.DONE) return;
                if (xhr.status !== 200 && xhr.status !== 201) return reject(xhr);
                const data = JSON.parse(xhr.responseText);
                console.log("Got answer: ", data);
                return data.code ? reject(xhr) : resolve(data);
            }
            xhr.open('POST', conf.apiUrl, true);
            xhr.setRequestHeader('Content-type', 'application/json');
            xhr.send(JSON.stringify(data));
        });
        await self.pc.setRemoteDescription(
            new RTCSessionDescription({ type: 'answer', sdp: session.sdp })
        );
        session.simulator = conf.schema + '//' + conf.urlObject.server + ':' + conf.port + '/rtc/v1/nack/';

        return session;
    };

    self.close = function (): void {
        self.pc && self.pc.close();
        self.pc = null;
    };

    self.ontrack = function (event: { track: MediaStreamTrack }): void {
        self.stream.addTrack(event.track);
    };

    self.__internal = {
        defaultPath: '/rtc/v1/play/',
        prepareUrl: function (webrtcUrl: string): any {
            const urlObject = self.__internal.parse(webrtcUrl);
            let schema = urlObject.user_query.schema;
            schema = schema ? schema + ':' : window.location.protocol;

            let port = urlObject.port || 1985;
            if (schema === 'https:') {
                port = urlObject.port || 443;
            }

            let api = urlObject.user_query.play || self.__internal.defaultPath;
            if (api.lastIndexOf('/') !== api.length - 1) {
                api += '/';
            }

            let apiUrl = schema + '//' + urlObject.server + ':' + port + api;
            for (const key in urlObject.user_query) {
                if (key !== 'api' && key !== 'play') {
                    apiUrl += '&' + key + '=' + urlObject.user_query[key];
                }
            }
            apiUrl = apiUrl.replace(api + '&', api + '?');

            const streamUrl = urlObject.url;

            let titi:any = new Date().getTime() * Math.random() * 100
            return {
                apiUrl: apiUrl, streamUrl: streamUrl, schema: schema, urlObject: urlObject, port: port,
                tid: Number(parseInt(titi)).toString(16).slice(0, 7)
            };
        },
        parse: function (url: string): any {
            const a = document.createElement("a");
            a.href = url.replace("rtmp://", "http://")
                .replace("webrtc://", "http://")
                .replace("rtc://", "http://");

            let vhost = a.hostname;
            let app = a.pathname.substring(1, a.pathname.lastIndexOf("/"));
            const stream = a.pathname.slice(a.pathname.lastIndexOf("/") + 1);

            app = app.replace("...vhost...", "?vhost=");
            if (app.indexOf("?") >= 0) {
                const params = app.slice(app.indexOf("?"));
                app = app.slice(0, app.indexOf("?"));

                if (params.indexOf("vhost=") > 0) {
                    vhost = params.slice(params.indexOf("vhost=") + "vhost=".length);
                    if (vhost.indexOf("&") > 0) {
                        vhost = vhost.slice(0, vhost.indexOf("&"));
                    }
                }
            }

            if (a.hostname === vhost) {
                const re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
                if (re.test(a.hostname)) {
                    vhost = "__defaultVhost__";
                }
            }

            let schema = "rtmp";
            if (url.indexOf("://") > 0) {
                schema = url.slice(0, url.indexOf("://"));
            }

            let port:any = a.port;
            if (!port) {
                if (schema === 'webrtc' && url.indexOf(`webrtc://${a.host}:`) === 0) {
                    port = (url.indexOf(`webrtc://${a.host}:80`) === 0) ? 80 : 443;
                }

                if (schema === 'http') {
                    port = 80;
                } else if (schema === 'https') {
                    port = 443;
                } else if (schema === 'rtmp') {
                    port = 1935;
                }
            }

            const ret:any = {
                url: url,
                schema: schema,
                server: a.hostname, port: port,
                vhost: vhost, app: app, stream: stream
            };
            self.__internal.fill_query(a.search, ret);

            if (!ret.port) {
                if (schema === 'webrtc' || schema === 'rtc') {
                    if (ret.user_query.schema === 'https') {
                        ret.port = 443;
                    } else if (window.location.href.indexOf('https://') === 0) {
                        ret.port = 443;
                    } else {
                        ret.port = 1985;
                    }
                }
            }

            return ret;
        },
        fill_query: function (query_string: string, obj: any): void {
            obj.user_query = {};

            if (query_string.length === 0) {
                return;
            }

            if (query_string.indexOf("?") >= 0) {
                query_string = query_string.split("?")[1];
            }

            const queries = query_string.split("&");
            for (let i = 0; i < queries.length; i++) {
                const elem = queries[i];
                const query = elem.split("=");
                obj[query[0]] = query[1];
                obj.user_query[query[0]] = query[1];
            }

            if (obj.domain) {
                obj.vhost = obj.domain;
            }
        }
    };
    let str:any = null
    self.pc = new RTCPeerConnection(str);
    self.stream = new MediaStream();

    self.pc.ontrack = function (event: RTCTrackEvent) {
        if (self.ontrack) {
            self.ontrack(event);
        }
    };

    return self;
}

export function SrsRtcWhipWhepAsync(): any {
    const self: any = {};

    self.constraints = {
        audio: true,
        video: {
            width: { ideal: 320, max: 576 }
        }
    };

    self.publish = async function (url: string): Promise<any> {
        if (url.indexOf('/whip/') === -1) throw new Error(`invalid WHIP url ${url}`);

        self.pc.addTransceiver("audio", { direction: "sendonly" });
        self.pc.addTransceiver("video", { direction: "sendonly" });

        if (!navigator.mediaDevices && window.location.protocol === 'http:' && window.location.hostname !== 'localhost') {
            throw new SrsError('HttpsRequiredError', `Please use HTTPS or localhost to publish, read https://github.com/ossrs/srs/issues/2762#issuecomment-983147576`);
        }
        const stream: MediaStream = await navigator.mediaDevices.getUserMedia(self.constraints);

        stream.getTracks().forEach(function (track: MediaStreamTrack) {
            self.pc.addTrack(track);
            self.ontrack && self.ontrack({ track: track });
        });

        const offer: RTCSessionDescriptionInit = await self.pc.createOffer();
        await self.pc.setLocalDescription(offer);
        const answer:any = await new Promise((resolve, reject) => {
            console.log("Generated offer: ", offer);

            const xhr = new XMLHttpRequest();
            xhr.onload = function () {
                if (xhr.readyState !== xhr.DONE) return;
                if (xhr.status !== 200 && xhr.status !== 201) return reject(xhr);
                const data:any = xhr.responseText;
                console.log("Got answer: ", data);
                return data.code ? reject(xhr) : resolve(data);
            }
            xhr.open('POST', url, true);
            xhr.setRequestHeader('Content-type', 'application/sdp');
            xhr.send(offer.sdp);
        });
        await self.pc.setRemoteDescription(
            new RTCSessionDescription({ type: 'answer', sdp: answer })
        );

        return self.__internal.parseId(url, offer.sdp, answer);
    };

    self.play = async function (url: string): Promise<any> {
        if (url.indexOf('/whip-play/') === -1 && url.indexOf('/whep/') === -1) throw new Error(`invalid WHEP url ${url}`);

        self.pc.addTransceiver("audio", { direction: "recvonly" });
        self.pc.addTransceiver("video", { direction: "recvonly" });

        const offer: RTCSessionDescriptionInit = await self.pc.createOffer();
        await self.pc.setLocalDescription(offer);
        const answer:any = await new Promise((resolve, reject) => {
            console.log("Generated offer: ", offer);

            const xhr = new XMLHttpRequest();
            xhr.onload = function () {
                if (xhr.readyState !== xhr.DONE) return;
                if (xhr.status !== 200 && xhr.status !== 201) return reject(xhr);
                const data:any = xhr.responseText;
                console.log("Got answer: ", data);
                return data.code ? reject(xhr) : resolve(data);
            }
            xhr.open('POST', url, true);
            xhr.setRequestHeader('Content-type', 'application/sdp');
            xhr.send(offer.sdp);
        });
        await self.pc.setRemoteDescription(
            new RTCSessionDescription({ type: 'answer', sdp: answer })
        );

        return self.__internal.parseId(url, offer.sdp, answer);
    };

    self.close = function (): void {
        self.pc && self.pc.close();
        self.pc = null;
    };

    self.ontrack = function (event: { track: MediaStreamTrack }): void {
        self.stream.addTrack(event.track);
    };
    let str:any =null
    self.pc = new RTCPeerConnection(str);
    self.stream = new MediaStream();

    self.__internal = {
        parseId: (url: string, offer: string, answer: string) => {
            let sessionid = offer.substr(offer.indexOf('a=ice-ufrag:') + 'a=ice-ufrag:'.length);
            sessionid = sessionid.substr(0, sessionid.indexOf('\n') - 1) + ':';
            sessionid += answer.substr(answer.indexOf('a=ice-ufrag:') + 'a=ice-ufrag:'.length);
            sessionid = sessionid.substr(0, sessionid.indexOf('\n'));

            const a = document.createElement("a");
            a.href = url;
            return {
                sessionid: sessionid,
                simulator: a.protocol + '//' + a.host + '/rtc/v1/nack/',
            };
        },
    };

    self.pc.ontrack = function (event: RTCTrackEvent) {
        if (self.ontrack) {
            self.ontrack(event);
        }
    };

    return self;
}

export function SrsRtcFormatSenders(senders: RTCRtpSender[], kind?: string): string {
    const codecs: string[] = [];
    senders.forEach(function (sender: any) {
        const params = sender.getParameters();
        params && params.codecs && params.codecs.forEach(function (c: RTCRtpCodecParameters) {
            if (kind && sender.track.kind !== kind) {
                return;
            }

            if (c.mimeType.indexOf('/red') > 0 || c.mimeType.indexOf('/rtx') > 0 || c.mimeType.indexOf('/fec') > 0) {
                return;
            }

            let s = '';

            s += c.mimeType.replace('audio/', '').replace('video/', '');
            s += ', ' + c.clockRate + 'HZ';
            if (sender.track.kind === "audio") {
                s += ', channels: ' + c.channels;
            }
            s += ', pt: ' + c.payloadType;

            codecs.push(s);
        });
    });
    return codecs.join(", ");
}